package com.aaie.gru.login.controller;

import com.aaie.gru.login.entity.LoginMessage;
import com.aaie.gru.login.entity.LoginUser;
import com.aaie.gru.notice.controller.GruSysNoticeController;
import com.aaie.gru.resource.entity.GruSysUserResource;
import com.aaie.gru.resource.service.IGruSysUserResourceService;
import com.aaie.gru.response.ResMessage;
import com.aaie.gru.user.entity.GruSysStu;
import com.aaie.gru.user.entity.GruSysUser;
import com.aaie.gru.user.mapper.GruSysUserMapper;
import com.aaie.gru.user.service.IGruSysUserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@Api(tags = "登录模块")
@RestController
public class LoginController {

    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);


    @Autowired
    IGruSysUserService gruSysUserService;

    @Autowired
    IGruSysUserResourceService gruSysUserResourceService;

    @ApiOperation(value = "登录", notes = "登录")
    @CrossOrigin
    @GetMapping("/login")
    public String login(String username, String password, String userClientId, String platform) {
        logger.info("==================>>>>>>>>>>>>>>username:" + username);
        logger.info("==================>>>>>>>>>>>>>>password:" + password);
        logger.info("==================>>>>>>>>>>>>>>userClientId:" + userClientId);
        logger.info("==================>>>>>>>>>>>>>>platform:" + platform);
        QueryWrapper<GruSysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_account", username);
        GruSysUser gruSysUser = gruSysUserService.getOne(queryWrapper);

        QueryWrapper<GruSysUser> queryWrapperStu = new QueryWrapper<>();
        queryWrapperStu.eq("stu_father_id",gruSysUser.getUserId());
        List<GruSysUser> listStu = gruSysUserService.getGruSysStuList(queryWrapperStu);

        if (gruSysUser == null) {
            return ResMessage.error("User does not exist!\n", 200);
        }
        if ("1".equals(gruSysUser.getDelFlag())) {
            return ResMessage.error("User deleted!", 200);
        }
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        Subject subject = SecurityUtils.getSubject();
        LoginMessage loginMessage = new LoginMessage();
        try {
            subject.login(token);
            if (StringUtils.isNotEmpty(userClientId)) {
                // 保存userClientId
                gruSysUser.setUserClientId(userClientId);
                gruSysUser.setPlatform(platform);
                gruSysUserService.saveOrUpdate(gruSysUser);
            }
            Session session = subject.getSession();
            //这里设置session过期时间
            session.setTimeout(-1000l);
            LoginUser loginUser = new LoginUser();
            BeanUtils.copyProperties(gruSysUser,loginUser);
            session.setAttribute("loginUser", loginUser);
            loginMessage.setToken(String.valueOf(subject.getSession().getId()));
            loginMessage.setUserRole(gruSysUser.getUserType());
            loginMessage.setUserAccount(gruSysUser.getUserAccount());
            loginMessage.setUserName(gruSysUser.getUserName());
            loginMessage.setGruSysUser(gruSysUser);
            loginMessage.setGruSysStuList(listStu);
            // 如果userClientId为空，则是pc登录，证明要返回菜单
            if (StringUtils.isEmpty(userClientId)) {
                QueryWrapper<GruSysUserResource> userResourceQueryWrapper = new QueryWrapper<>();
                userResourceQueryWrapper.like("user_role", gruSysUser.getUserType());
                List<GruSysUserResource> gruSysUserResourceList = gruSysUserResourceService.list(userResourceQueryWrapper);
                if (!CollectionUtils.isEmpty(gruSysUserResourceList)) {
                    List<String> resourceList = new ArrayList<>();
                    for (GruSysUserResource gruSysUserResource : gruSysUserResourceList) {
                        resourceList.add(gruSysUserResource.getResourceName());
                    }
                    loginMessage.setResourceList(resourceList);
                }
            }
            return ResMessage.ok(loginMessage);
        } catch (Exception e) {
            e.printStackTrace();
            return ResMessage.error("Username or password is incorrect!", 200);
        }
    }

    @ApiOperation(value = "未登录", notes = "未登录")
    @CrossOrigin
    @GetMapping("/unlogin")
    public String unlogin() {
        return ResMessage.error("未登录", 204);
    }

    @ApiOperation(value = "登出", notes = "登出")
    @CrossOrigin
    @GetMapping("/logout")
    public String logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return ResMessage.ok("退出成功");
    }
}